package com.siyoumi.app.modules.redbook.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.RedbookData;
import com.siyoumi.app.entity.RedbookQuan;
import com.siyoumi.app.entity.SysUser;
import com.siyoumi.app.modules.redbook.entity.EnumRedbookQuanType;
import com.siyoumi.app.modules.redbook.service.SvcRedbookData;
import com.siyoumi.app.modules.redbook.service.SvcRedbookQuan;
import com.siyoumi.app.modules.redbook.vo.RedbookSetData;
import com.siyoumi.app.modules.redbook.vo.VaRedBookQuan;
import com.siyoumi.app.service.RedbookQuanService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XEnumBase;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wxapp/redbook/api")
public class ApiRedbook
        extends WxAppApiController {
    /**
     * 项目列表
     */
    @GetMapping("list")
    public XReturn list() {
        InputData inputData = InputData.fromRequest();

        String[] select = {
                "rquan_id",
                "rquan_create_date",
                "rquan_uid",
                "rquan_type",
                "rquan_content_src",
                "rquan_title",
                "rquan_content",
                "rquan_url",
                "rquan_good_count",
                "rquan_collect_count",
                "rquan_comment_count",
                "user_name",
        };
        JoinWrapperPlus<RedbookQuan> query = SvcRedbookQuan.getBean().listQuery(inputData);
        query.join(SysUser.table(), SysUser.tableKey(), "rquan_uid");
        query.eq("rquan_enable", 1).eq("rquan_uid", getUid());
        query.select(select);

        IPage<RedbookQuan> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcRedbookQuan.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //
        EnumRedbookQuanType enumRedbookQuanType = XEnumBase.of(EnumRedbookQuanType.class);
        //
        for (Map<String, Object> data : list) {
            RedbookQuan entity = SvcRedbookQuan.getApp().loadEntity(data);
            data.put("type", enumRedbookQuanType.get(entity.getRquan_type()));
        }

        getR().setData("list", list);

        return getR();
    }


    /**
     * 详情
     *
     * @return
     */
    @GetMapping("info")
    public XReturn info() {
        String quanId = input("quan_id");
        if (XStr.isNullOrEmpty(quanId)) {
            return EnumSys.MISS_VAL.getR("miss quan_id");
        }
        RedbookQuan entityQuan = SvcRedbookQuan.getApp().first(quanId);
        if (entityQuan == null) {
            return EnumSys.ERR_VAL.getR("id异常");
        }

        Map<String, Object> mapQuan = XBean.toMap(entityQuan, new String[]{
                "rquan_id",
                "rquan_create_date",
                "rquan_uid",
                "rquan_type",
                "rquan_title",
                "rquan_content",
                "rquan_url",
                "rquan_good_count",
                "rquan_collect_count",
                "rquan_comment_count",
        });
        getR().setData("quan", mapQuan);
        //点赞
        getR().setData("is_good", SvcRedbookData.getBean().getEntity(0, entityQuan.getKey(), getUid()) != null);
        //收藏
        getR().setData("is_collect", SvcRedbookData.getBean().getEntity(1, entityQuan.getKey(), getUid()) != null);

        return getR();
    }

    //添加
    @PostMapping("edit")
    public XReturn edit(@Validated VaRedBookQuan vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        InputData inputData = InputData.fromRequest();
        if (inputData.isAdminAdd()) {
            vo.setRquan_uid(getUid());
        }

        RedbookQuanService app = SvcRedbookQuan.getApp();

        List<String> ignoreField = new ArrayList<>();
        if (isAdminEdit()) {
            ignoreField.add("rquan_group_id");
            ignoreField.add("rquan_uid");
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = app.saveEntity(inputData, vo, true, ignoreField);
            if (r.ok()) {

            }
            return r;
        });
    }


    //删除
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/del")
    public XReturn del(String[] ids) {
        return SvcRedbookQuan.getBean().delete(Arrays.asList(ids), getUid());
    }

    //点赞，收藏
    @PostMapping("set_data")
    public XReturn setData(@Validated RedbookSetData vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        vo.setRdata_uid(getUid());
        return SvcRedbookData.getBean().setData(vo);
    }

    @GetMapping("list_data_to")
    //被点赞，被收藏
    public XReturn listDataTo() {
        Integer type = XStr.toInt(input("type", "0"));


        String[] select = {
                "rdata_id",
                "rdata_create_date",
                "rquan_id",
                "rquan_title",
                "rquan_url",
                "user_id",
                "user_name",
                "user_headimg",
        };
        JoinWrapperPlus<RedbookData> query = SvcRedbookData.getBean().listQuery(type, null);
        query.join(SysUser.table(), SysUser.tableKey(), "rdata_uid");
        query.join(RedbookQuan.table(), RedbookQuan.tableKey(), "rdata_id_src");
        query.select(select);
        query.eq("rquan_enable", 1)
                .eq("rquan_uid", getUid());
        query.orderByDesc("rdata_create_date")
                .orderByAsc("rdata_id");

        IPage<RedbookData> page = new Page<>(getPageIndex(), getPageSize(), false);
        //list
        IPage<Map<String, Object>> pageData = SvcRedbookData.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        //
        //for (Map<String, Object> data : list) {
        //    RedbookQuan entity = SvcRedbookQuan.getApp().loadEntity(data);
        //}

        getR().setData("type", type);
        getR().setData("list", list);

        return getR();
    }
}
